package com.excample.interupt;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * @Author: sn
 * @Desc 线程中断测试
 * @Date: 2021/8/30
 */
public class ThreadInterrupt {

    public static void main(String[] args) {
        Thread t = new Thread(new Run3());
        t.start();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
    }
}


/**
 * 识别到中断标记，但是还会执行跳出循环的操作
 */
class Run1 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 500000; i++) {
            if (Thread.interrupted()) {
                System.out.println("should be stopped and exit");
                break;
            }
            System.out.println("i=" + (i + 1));
        }
        System.out.println("this line is also executed. thread does not stopped");//尽管线程被中断,但并没有结束运行。这行代码还是会被执行
    }
}


/**
 * 识别到中断标志，抛出异常，截获，后面代码没用执行
 */
class Run2 implements Runnable{

    @Override
    public void run() {
        try{
            for (int i = 0; i < 500000; i++) {
                if (Thread.interrupted()) {
                    System.out.println("should be stopped and exit");
                    throw new InterruptedException();
                }
                System.out.println("i=" + (i + 1));
            }
            System.out.println("this line cannot be executed. cause thread throws exception");//这行语句不会被执行!!!
        }catch(InterruptedException e){
            System.out.println("catch interrupted exception");
            e.printStackTrace();
        }
    }
}

class Run3 implements Runnable{

    @Override
    public void run() {
        try{
            for (int i = 0; i < 500000; i++) {
                if (Thread.interrupted()) {
                    System.out.println("should be stopped and exit");
                    throw new InterruptedException();
                }
                System.out.println("i=" + (i + 1));
            }
            System.out.println("this line cannot be executed. cause thread throws exception");//这行语句不会被执行!!!
        }catch(InterruptedException e){
            /*System.out.println("catch interrupted exception");
            e.printStackTrace();*/
            Thread.currentThread().interrupt();//这样处理比较好
        }
    }
}
